#include "exportcommand.h"
#include "mainwindow.h"
#include "mergedexportmanager.h"
#include "unifiedpagerenderer.h"
#include "statusbarmanager.h"
#include "customfilebrowser.h"
#include <QDebug>
#include <QThread>
#include <QStandardPaths>
#include <QDir>
#include <QDateTime>

ExportCommand::ExportCommand(MainWindow* mainWindow, QObject* parent)
    : QObject(parent)
    , m_mainWindow(mainWindow)
    , m_workerThread(nullptr)
    , m_exportManager(nullptr)
    , m_pageRenderer(nullptr)
    , m_isActive(false)
{
    initializeWorker();
}

ExportCommand::~ExportCommand()
{
    if (m_workerThread && m_workerThread->isRunning()) {
        m_workerThread->quit();
        m_workerThread->wait(5000); // 最多等待5秒
    }

    if (m_workerThread) {
        m_workerThread->deleteLater();
    }
}

void ExportCommand::initializeWorker()
{
    // 创建工作线程
    m_workerThread = new QThread(this);
    m_worker = std::make_unique<AsyncExportWorker>();
    m_worker->moveToThread(m_workerThread);

    // 连接信号
    connect(m_worker.get(), &AsyncExportWorker::taskStarted,
            this, &ExportCommand::onTaskStarted);
    connect(m_worker.get(), &AsyncExportWorker::taskCompleted,
            this, &ExportCommand::onTaskCompleted);
    connect(m_worker.get(), &AsyncExportWorker::taskFailed,
            this, &ExportCommand::onTaskFailed);
    connect(m_worker.get(), &AsyncExportWorker::taskCancelled,
            this, &ExportCommand::onTaskCancelled);

    // 连接进度通知器
    connect(m_worker->getProgressNotifier(), &SimpleProgressNotifier::UIUpdateRequested,
            this, &ExportCommand::onUIUpdateRequested);

    // 启动工作线程
    m_workerThread->start();

}

void ExportCommand::execute()
{

    if (m_isActive) {
        return;
    }

    // 获取当前文件列表
    QList<UnifiedFileInfo> files = getCurrentFiles();

    if (files.isEmpty()) {
        qWarning() << "[ExportCommand] 没有选择要导出的文件";
        emit exportFailed("没有选择要导出的文件");
        return;
    }

    // 生成输出路径
    QString outputPath = generateOutputPath();
    if (outputPath.isEmpty()) {
        qWarning() << "[ExportCommand] 无法生成输出路径";
        emit exportFailed("无法生成输出路径");
        return;
    }

    // 创建导出任务
    AsyncExportWorker::ExportTask task;
    task.files = files;
    task.settings = ProcessingSettings(); // TODO: 从主窗口获取当前处理设置
    task.outputPath = outputPath;
    task.taskId = QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss-zzz");

    // 获取主窗口当前显示的页面（确保所见即所得）
    task.displayedPages = getCurrentDisplayedPagesFromMainWindow();


    m_isActive = true;
    m_currentTaskId = task.taskId;

    // 提交任务到工作线程
    QMetaObject::invokeMethod(m_worker.get(), [this, task]() {
        m_worker->submitTask(task);
    }, Qt::QueuedConnection);

}

void ExportCommand::cancel()
{
    if (!m_isActive) {
        return;
    }


    QMetaObject::invokeMethod(m_worker.get(), &AsyncExportWorker::cancelCurrentTask, Qt::QueuedConnection);
}

void ExportCommand::pause()
{
    if (!m_isActive) {
        return;
    }


    QMetaObject::invokeMethod(m_worker.get(), &AsyncExportWorker::pauseCurrentTask, Qt::QueuedConnection);
}

void ExportCommand::resume()
{
    if (!m_isActive) {
        return;
    }


    QMetaObject::invokeMethod(m_worker.get(), &AsyncExportWorker::resumeCurrentTask, Qt::QueuedConnection);
}

bool ExportCommand::isActive() const
{
    return m_isActive && m_worker && m_worker->isProcessing();
}

bool ExportCommand::isPaused() const
{
    return m_worker && m_worker->isPaused();
}

void ExportCommand::setExportManager(MergedExportManager* manager)
{
    // 🔧 Martin Fowler重构：移除对MergedExportManager的依赖
    // 新的AsyncExportWorker直接处理导出，避免线程冲突
    Q_UNUSED(manager);
}

void ExportCommand::setPageRenderer(UnifiedPageRenderer* renderer)
{
    // 🔧 Martin Fowler重构：暂时保留，但简化实现
    // 未来版本中可能会完全移除这个依赖
    m_pageRenderer = renderer;
    Q_UNUSED(m_pageRenderer); // 暂时不使用
}

QString ExportCommand::generateOutputPath() const
{
    QString timestamp = QDateTime::currentDateTime().toString("MMdd-hhmm");
    QString documentsPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    QString exportDir = documentsPath + "/PDF导出";

    // 确保导出目录存在
    QDir dir;
    if (!dir.exists(exportDir)) {
        dir.mkpath(exportDir);
    }

    return QString("%1/材料-%2.pdf").arg(exportDir).arg(timestamp);
}

QList<UnifiedFileInfo> ExportCommand::getCurrentFiles() const
{
    if (!m_mainWindow) {
        return QList<UnifiedFileInfo>();
    }

    // 通过MainWindow的getFileBrowser()方法获取文件浏览器
    CustomFileBrowser* fileBrowser = m_mainWindow->getFileBrowser();
    if (!fileBrowser) {
        return QList<UnifiedFileInfo>();
    }

    QList<UnifiedFileInfo> files = fileBrowser->getFiles();

    return files;
}

void ExportCommand::onTaskStarted(const QString& taskId)
{
    emit exportStarted(taskId);
}

void ExportCommand::onTaskCompleted(const QString& taskId, const QString& outputPath)
{

    m_isActive = false;
    m_currentTaskId.clear();

    emit exportCompleted(outputPath);
}

void ExportCommand::onTaskFailed(const QString& taskId, const QString& error)
{
    qCritical() << "[ExportCommand] Task failed:" << taskId << "error:" << error;

    m_isActive = false;
    m_currentTaskId.clear();

    emit exportFailed(error);
}

void ExportCommand::onTaskCancelled(const QString& taskId)
{

    m_isActive = false;
    m_currentTaskId.clear();

    emit exportCancelled();
}

void ExportCommand::onUIUpdateRequested(const QString& text, const QColor& color)
{
    updateStatusBar(text, color);
}

QList<QImage> ExportCommand::getCurrentDisplayedPagesFromMainWindow()
{
    QList<QImage> displayedPages;

    if (!m_mainWindow) {
        qWarning() << "[ExportCommand] MainWindow未设置";
        return displayedPages;
    }

    // 获取主窗口的PageView
    PageView* pageView = m_mainWindow->getPageView();
    if (!pageView) {
        qWarning() << "[ExportCommand] 无法获取PageView";
        return displayedPages;
    }

    // 获取PageView当前显示的页面
    displayedPages = pageView->getPages();


    return displayedPages;
}

void ExportCommand::updateStatusBar(const QString& text, const QColor& color)
{
    // TODO: 更新状态栏显示
    // 这里需要与StatusBarManager集成
    if (m_mainWindow) {
        // 调用MainWindow的状态栏更新方法
    }
}